package com.faiz.algorithm;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Courses {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        // 数据准备，首先构建邻接表和入度矩阵
        List<List<Integer>> adjacency = new ArrayList<>();
        int[] inDegrees = new int[numCourses];
        for (int i = 0; i < numCourses; i++) {
            adjacency.add(new ArrayList<>());
        }
        for (int[] pair : prerequisites) {
            adjacency.get(pair[1]).add(pair[0]);
            inDegrees[pair[0]]++;
        }

        // 对入度为零的进行处理
        Queue<Integer> queue = new LinkedList<>();
        for (int i = 0; i < numCourses; i++) {
            if (inDegrees[i] == 0) {
                queue.offer(i);
            }
        }

        while (!queue.isEmpty()) {
            int i = queue.poll();
            for (int num : adjacency.get(i)) {
                inDegrees[num]--;
                if (inDegrees[num] == 0) {
                    queue.offer(num);
                }
            }
        }

        for (int num : inDegrees) {
            if (num != 0) {
                return false;
            }
        }

        return true;
    }

    public static void main(String[] args) {
        Courses courses = new Courses();
        int[][] prerequisites = {{0, 1}};
        System.out.println(courses.canFinish(2, prerequisites));
    }
}
